package com.chenxi.vhr.controller.system.basic;

import com.chenxi.vhr.bean.BaseDepartment;
import com.chenxi.vhr.bean.common.Result;
import com.chenxi.vhr.bean.vo.DepartmentTreeVo;
import com.chenxi.vhr.service.BaseDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author : zhangchenxi
 * @create : 2022-02-07
 **/
@RestController
@RequestMapping("/system/basic/department")
public class DeptController {

    @Autowired
    BaseDepartmentService departmentService;

    @GetMapping
    public Result list () {
        List<DepartmentTreeVo> list = departmentService.getDeptTree();
        return Result.ok("查询成功", list);
    }

    // 这里调用存储过程
    @PostMapping
    public Result addDept(@RequestBody BaseDepartment department) {
        // 存储过程的执行输出结果回返回到实体对象中
        departmentService.addDept(department);
        return department.getUpdCount() == 1 ? Result.ok("新增成功", department) : Result.error("新增失败", department);
    }

    @DeleteMapping("/{deptId}")
    public Result deleteDept(@PathVariable Integer deptId) {
        BaseDepartment baseDepartment = new BaseDepartment();
        baseDepartment.setId(deptId);
        departmentService.deleteDept(baseDepartment);
        Integer updCount = baseDepartment.getUpdCount();
        if (updCount == -1) {
            return Result.error("删除失败：当前部门是下有员工关联！");
        } else if (updCount == -2) {
            return Result.error("删除失败：当前部门下存在子部门！");
        } else if (updCount == 1) {
            return Result.ok("删除成功！");
        }
        return Result.error("删除失败");
    }
}
